import { defineStore } from "pinia";
import { computed, ref, reactive } from "vue";
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
// import type {
//   loginFormData,
//   loginResponseData,
//   userInfoReponseData,
// } from "@/api/user/type";
//引入路由(常量路由)
import { constantRoute } from "@/router/routes";

export const useUserStore = defineStore(
  "user",
  () => {
    // 声明数据
    let token = ref("");
    // 声明方法
    //用户登录的方法
    const userLogin = async (data: any) => {
      const result: any = await reqLogin(data);
      console.log(result);
      
      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      if (result.code == 200) {
        token.value = result.data as string;
      //   //能保证当前async函数返回一个成功的promise
      //   return "ok";
      // } else {
      //   return Promise.reject(new Error(result.data));
      }
    };
    let name = ref("");
    let avatar = ref("");
    let buttons = ref([]);
    //获取用户信息方法
    const getUserInfo = async () => {
      let result: any = await reqUserInfo();
      //如果获取用户信息成功，存储一下用户信息
      if (result.code == 200) {
        console.log(666, "获取信息成功");
        name.value = result.data.name;
        avatar.value = result.data.avatar;
        buttons.value = result.data.buttons;
        // console.log(name.value,avatar.value,buttons.value);

        //计算当前用户需要展示的异步路由
        // const userAsyncRoute = filterAsyncRoute(
        //   cloneDeep(asnycRoute),
        //   result.data.routes,
        // )
        // //菜单需要的数据整理完毕
        // this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute]
        // //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        // ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
        //   router.addRoute(route)
        // })
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    };
    //退出登录
    const userLogout = async () => {
      //退出登录请求
      const result = await reqLogout();
      if (result.code == 200) {
        token.value = "";
        name.value = "";
        avatar.value = "";
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    };
    // 声明计算属性
    // const computedList = computed(() => count.value * 2);

    // 声明数据
    const menuRoutes = constantRoute; //仓库存储生成菜单需要数组(路由)
    return {
      token,
      userLogin,
      menuRoutes,
      name,
      avatar,
      buttons,
      getUserInfo,
      userLogout,
    };
  },
  {
    persist: {
      paths: ["token", "name", "avatar"],
    },
  }
);
